package com.sky.zzh.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;

import com.sky.zzh.R;


public class AsyncTaskImageLoad extends AsyncTask<String, Integer, Bitmap> {

    private ImageView Image=null;
    //SoftReference是软引用，是为了更好的为了系统回收变量  
//    public static HashMap<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>(); 
    
    public AsyncTaskImageLoad(ImageView img) 
    {
        Image=img;
    }
    //运行在子线程中
    protected Bitmap doInBackground(String... params) {
//		Log.i("bbb", "doInBackgroundresult:" + params[0]);
//        if (imageCache.containsKey(params[0])) {  	//判断imageCache是否包含params[0]，包含则反悔true，反之为false
//            //从缓存中获取  
//            SoftReference<Bitmap> softReference = imageCache.get(params[0]);  
//            Bitmap bitmap = softReference.get();  
//            if (bitmap != null) {  
//                return bitmap;  
//            }  
//        }
        try 
        {
			Log.i("bbb", "URLresult:" + params[0]);
			URL url = new URL(params[0]);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestProperty("AccessToken", "123456789");
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			int result = conn.getResponseCode();
			System.out.println("imageCode:"+result);
			if (result == 200) {
				Log.i("bbb", "result:" + params[0]);
				// 用try catch 块包围住
				BitmapFactory.Options opt = new BitmapFactory.Options();
				InputStream input = conn.getInputStream();
				BufferedInputStream bIn = new BufferedInputStream(input);
				ByteArrayOutputStream bout = new ByteArrayOutputStream();
				byte buffer[] = new byte[1024 * 64];
				int len;
				while ((len = bIn.read(buffer)) != -1) {
					bout.write(buffer, 0, len);
				}
				byte b[] = bout.toByteArray();
				bout.flush();
				bout.close();
				bIn.close();
				BitmapFactory.Options opts = new BitmapFactory.Options();
				opts.inJustDecodeBounds = true;
				BitmapFactory.decodeByteArray(b, 0, b.length, opt);
				// opt.inJustDecodeBounds = false;
				opt.inSampleSize = calcSampleSize(opts);
				opt.inPurgeable = true;
				opt.inPreferredConfig = Config.RGB_565;
				opt.inInputShareable = true;
				opts.inJustDecodeBounds = false;
				Bitmap map = BitmapFactory.decodeByteArray(b, 0, b.length, opt);
				// 将要 释放的 bitmap也添加到list里
//				imageCache.put(params[0], new SoftReference<Bitmap>(map));
				return map;
			}
        } catch (Exception e) 
        {
            e.printStackTrace();
            Log.i("bbb", "e:" + e.toString()); 
        }
        return null;
    }

	private class ImageSize {
		int imgHeight;
		int imgWidth;
	}

	private int calcSampleSize(Options opts) {
		ImageSize size = getImageSize();
		int sampleSize = 1;
		int reqHeight = size.imgHeight;
		int reqWidth = size.imgWidth;
		if (reqHeight < opts.outHeight && reqWidth < opts.outWidth) {
			int widthRatio = Math.round((float) opts.outWidth
					/ (float) reqWidth);
			int heightRatio = Math.round((float) opts.outHeight
					/ (float) reqHeight);
			sampleSize = Math.max(widthRatio, heightRatio);
		}
		return sampleSize;
	}

	private ImageSize getImageSize() {
		ImageSize size = new ImageSize();
		LayoutParams params = Image.getLayoutParams();
		int width = params.width == LayoutParams.WRAP_CONTENT ? 0
				: params.width;
		int height = params.height == LayoutParams.WRAP_CONTENT ? 0
				: params.height;
		if (width < 0) {
			width = getImageViewFieldValue("mMaxValue");
		}
		DisplayMetrics metrics = Image.getResources().getDisplayMetrics();
		if (width < 0) {
			width = metrics.widthPixels;
		}
		if (height < 0) {
			height = getImageViewFieldValue("mMaxValue");
		}
		if (height < 0) {
			height = metrics.heightPixels;
		}
		size.imgWidth = width;
		size.imgHeight = height;
		return size;
	}

	private int getImageViewFieldValue(String string) {
		try {
			Field f = ImageView.class.getDeclaredField(string);
			f.setAccessible(true);
			int value = 0;
			int fieldValue = (Integer) f.get(Image);
			if (fieldValue > value && fieldValue < Integer.MAX_VALUE) {
				value = fieldValue;
			}
			return value;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return 0;
	}
    
	protected void onPostExecute(Bitmap result)
    {
        if(Image!=null && result!=null)
        {
        	Image.setBackgroundResource(R.color.color_full_transparent);
        	System.out.println("image success");
            Image.setImageBitmap(result);
        }
        
        super.onPostExecute(result);
    }
}
